package com.yanqu.road.timer;

import com.yanqu.road.utils.executor.ScheduledThreadPoolHelper;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author duli
 * @version 1.0
 * @date 2020/9/9 14:24
 * @Description 所有的定时器写在这边
 */
public class GeneralAgentTimerMgr {
    private static final Logger log = LogManager.getLogger(GeneralAgentTimerMgr.class.getName());
    private static ScheduledExecutorService timerExecutorService;
    private static ReceiveDataSaveTask receiveDataSaveTask = null;
    private static CheckServerIdTask checkServerIdTask=null;
    private static DataAnalyticFlushTask dataAnalyticFlushTask=null;

    public static synchronized boolean initGlobalTimers() {
        //初始化定时器线程池
        int corePoolSize = Runtime.getRuntime().availableProcessors() * 2;
        corePoolSize = Math.min(8, Math.max(4, corePoolSize));
        timerExecutorService = ScheduledThreadPoolHelper.createGameScheduledThreadPoolExecutor(corePoolSize, "timer-logAnalysis");

        int interval;
        interval = 5;
        if (null == receiveDataSaveTask) {
            receiveDataSaveTask = new ReceiveDataSaveTask();
            timerExecutorService.scheduleWithFixedDelay(receiveDataSaveTask, interval, 30, TimeUnit.SECONDS);
        }
        if (null == checkServerIdTask) {
            checkServerIdTask = new CheckServerIdTask();
            timerExecutorService.scheduleWithFixedDelay(checkServerIdTask, 0, interval, TimeUnit.MINUTES);
        }
        if (null == dataAnalyticFlushTask) {
            dataAnalyticFlushTask = new DataAnalyticFlushTask();
            timerExecutorService.scheduleWithFixedDelay(dataAnalyticFlushTask, 0, 30, TimeUnit.SECONDS);
        }

        return true;
    }

    public static void stop() {
        cancelTask(receiveDataSaveTask);
    }

    private static void cancelTask(GeneralTask task) {
        if (null != task) {
            task.cancel(true);
        }
    }
}
